package com.jt.service;

import com.jt.vo.EasyUIImage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
@PropertySource("classpath:/properties/image.properties")//引入配置文件
public class FileServiceImpl implements FileService {

    @Value("${image.localFileDir}")
    private String localFileDir;//服务器本地磁盘存储路径
    @Value("${image.urlPath}")
    private String urlPath;//虚拟访问路径

    @Override
    public EasyUIImage uploadFile(MultipartFile uploadFile) {
        EasyUIImage uiImage = new EasyUIImage();
        //1.获取图片名称
        String fileName = uploadFile.getOriginalFilename().toLowerCase();//要注意把大写转换成小写
        //2.通过正则表达式判断是不是图片
        if (!fileName.matches("^.+\\.(jpg|png|gif)$")) {
            uiImage.setError(1);//表示不是图片
            return uiImage;
        }

        //3.通过判断是否有宽度和高度判断是否是图片，还是木马病毒伪装的文件
        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0) {
                uiImage.setError(1);//不是图片文件就终止程序
                return uiImage;
            }
            uiImage.setWidth(width).setHeight(height);

            //4.以时间格式进行数据存储
            String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            //合成最终图片上传路径
            String localdir = localFileDir + dateDir;
            File dirFile = new File(localdir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            //5.以UUID重新生成图片名称
            String uuid = UUID.randomUUID().toString().replace("-", "");//去掉原来的横杠-
            //获取图片的后缀
            String fileType = fileName.substring(fileName.lastIndexOf("."));//从后往前找第一个.的位置，并把后面的字符串截取
            //拼接
            String realFileName = uuid + fileType;

            //6.实现文件上传
            //D:/1-JT/jt-image/yyyy/MM/dd/uuid.jpg
            String realPath = localdir + "/" + realFileName;
            File realFile = new File(realPath);
            uploadFile.transferTo(realFile);
            System.out.println("文件上传成功！");

            //urlPath  http://image.jt.com/yyyy/MM/dd/uuid.jpg
            String url = urlPath + dateDir + "/" + realFileName;
            uiImage.setUrl(url);

        } catch (Exception e) {
            e.printStackTrace();
            uiImage.setError(1);//程序出错，上传终止
        }
        return uiImage;
    }

}
